import {
    Viewer,
    Ellipsoid,
    GeographicProjection,
    ImageryLayer,
    Ion,
    Color as CesiumColor,
    PostProcessStageLibrary ,
    ArcGisMapServerImageryProvider,
    SingleTileImageryProvider,
    Primitive,
    GeometryInstance,
    RectangleGeometry,
    Rectangle,
    EllipsoidSurfaceAppearance,
    Math as  CesiumMath,
    Cartesian3,
    Material
} from  'cesium'
  /**
   * 初始化cesium的地图
   * @param extent
   */
 export  const  initMap=(id:string,extent:Array<number>)=>{
    let cgs2000Ellipsolid = new Ellipsoid(6378137.0, 6378137.0, 6356752.31414035585)
    var cgs2000GeographicProj = new GeographicProjection(cgs2000Ellipsolid)
    Ion.defaultAccessToken =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1ODRiY2NiYi1jMmVlLTRkNTctYTNhNy03ZGNlMGQ2YmNjZTQiLCJpZCI6MTQwMDIsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1NjQ1NTU1MDV9.6E9-n__jfDwX1e-C3H685NhJZ8HUx3BQ7FYEJ9Rz9Ec'
    let viewer:any = new Viewer(id, {
      infoBox: false,
      geocoder: false,
      mapProjection: cgs2000GeographicProj,
      fullscreenButton: false,
      homeButton: false, //是否显示Home按钮
      sceneModePicker: false, //是否显示3D/2D选择器
      // baseLayerPicker: false,//是否显示图层选择器
      navigationHelpButton: false, //是否显示右上角的帮助按钮
      navigationInstructionsInitiallyVisible: false,
      animation: true, //是否创建动画小器件，左下角仪表
      timeline: true, //是否显示时间轴
      vrButton: false,
      selectionIndicator: false, //是否显示选取指示器组件
      requestRenderMode: true,  //开启显示渲染
      maximumRenderTimeChange:Infinity, //开启显示渲染
      showRenderLoopErrors: true, //是否显示渲染错误
      //baseLayerPicker和imageryProvider同时存在避免api.cesium.com
      baseLayerPicker: false,
      //解决图片打印问题
      contextOptions: {
        webgl: {
          alpha: true,
          depth: true,
          stencil: true,
          antialias: true,
          premultipliedAlpha: true,
          //通过canvas.toDataURL()实现截图需要将该项设置为true
          preserveDrawingBuffer: true,
          failIfMajorPerformanceCaveat: true
        }
      },
        baseLayer: new ImageryLayer(new SingleTileImageryProvider({
            url: '',
            tileWidth:255,
            tileHeight:255
        })) ,
        // baseLayer:ImageryLayer.fromProviderAsync(
        //      ArcGisMapServerImageryProvider.fromUrl(
        //         "https://ibasemaps-api.arcgis.com/arcgis/rest/services/World_Imagery/MapServer", {token: "<ArcGIS Access Token>"})
        //     //     ArcGisMapServerImageryProvider.fromBasemapType(ArcGisBaseMapType.SATELLITE)
        // ),
    })
    viewer.scene.requestRender();
    // let _this = this
    // viewer._cesiumWidget._creditContainer.style.display = 'none' //隐藏版权信息
    //是否开启抗锯齿
    viewer.scene.postProcessStages.fxaa.enabled = false
    viewer.scene.screenSpaceCameraController.enableCollisionDetection = false
   const baseColor=CesiumColor.fromCssColorString('#000');
    viewer.scene.globe.baseColor = baseColor;
    // viewer.scene.globe.depthTestAgainstTerrain = true;
    var stages = viewer.scene.postProcessStages;
    viewer.scene.brightness = viewer.scene.brightness || stages.add(PostProcessStageLibrary.createBrightnessStage());
    viewer.scene.brightness.enabled = true;
    viewer.scene.brightness.uniforms.brightness = Number(1.23);
    // 时间轴的timeline:true 和  animation:true,因为轨迹需要，使用下面方式隐藏组件
    const timeLineContain:HTMLElement = <HTMLElement>document.querySelector(".cesium-viewer-timelineContainer");
    if(timeLineContain){
        timeLineContain.style.display = 'none';
    }
    const animateContain:HTMLElement= <HTMLElement> document.querySelector(".cesium-viewer-animationContainer");
    if(animateContain!==null){
        animateContain.style.display = 'none';
    }
     return viewer;
 }


/**
 * uniform还可以传入时间，生成动态效果
 * @param viewer
 */
export const  createPrimitives=(viewer:any)=> {
   const primitive= viewer.scene.primitives.add(
        new Primitive({
            geometryInstances: new GeometryInstance({
                geometry: new RectangleGeometry({
                    rectangle: Rectangle.fromDegrees(116, 39, 117, 39.7),
                    vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT,
                })
            }),
            appearance: new EllipsoidSurfaceAppearance({
                aboveGround: false
            })
        })
    )
    viewer.camera.flyTo({
        destination : Cartesian3.fromDegrees(116.5, 39.35, 180000.0),
        orientation : {
            heading : CesiumMath.toRadians(0),
            pitch : CesiumMath.toRadians(-90.0),
            roll : 0.0
        }
    });
    //图片纹理
    const primitive1= viewer.scene.primitives.add(
        new Primitive({
            geometryInstances: new GeometryInstance({
                geometry: new RectangleGeometry({
                    rectangle: Rectangle.fromDegrees(118, 39, 119, 39.7),
                    vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT,
                })
            }),
            appearance: new EllipsoidSurfaceAppearance({
                aboveGround: false
            })
        })
    )
    primitive1.appearance.material=new Material({
        fabric:{
            uniforms:{
                image:'/fj.jpeg' ,
                alpha:1.0
            },
            source:`
            czm_material czm_getMaterial(czm_materialInput materialInput){
                            czm_material material=czm_getDefaultMaterial(materialInput);
                            material.diffuse=texture(image,materialInput.st).rgb;
                            return material;
                        }
            `
        }
    })
    //挖孔
    const primitive2= viewer.scene.primitives.add(
        new Primitive({
            geometryInstances: new GeometryInstance({
                geometry: new RectangleGeometry({
                    rectangle: Rectangle.fromDegrees(116, 38, 117, 38.7),
                    vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT,
                })
            }),
            appearance: new EllipsoidSurfaceAppearance({
                aboveGround: false
            })
        })
    )
    primitive2.appearance.material=new Material({
        fabric:{
            uniforms:{
                image:'/fj.jpeg' ,
                alpha:1.0
            },
            source: `
              czm_material czm_getMaterial(czm_materialInput materialInput){
                            czm_material material=czm_getDefaultMaterial(materialInput);
                            material.diffuse=texture(image,materialInput.st).rgb;
                            material.alpha=alpha;
                            vec2 center=vec2(0.5,0.5);            
                            float dis=distance(center,materialInput.st);
                            if(dis>0.25){
                                material.diffuse=vec3(1.0,0.0,0.0);
                            }
                            if(dis<0.1){
                                material.diffuse=vec3(1.0);
                            }
                            return material;
                        }
            `
        }
    })

}


 function  createColorCanvas(color:string){
    var width = 1,
    height = 1
  var canvas = document.createElement('canvas')
  canvas.id = '20211216'
  canvas.width = width
  canvas.height = height
  let ctx = canvas.getContext('2d')
  ctx !== null 
  if(ctx!==null){
    ctx.fillStyle = color
    ctx.fillRect(0, 0, width, height)
  }
  return canvas.toDataURL()
 }
